<?php

namespace addons\alidayu;

use app\common\library\Menu;
use think\Addons;
use addons\alidayu\library\SignatureHelper;

/**
 * 插件
 */
class Alidayu extends Addons
{

    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {
        
        return true;
    }

    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        
        return true;
    }

    /**
     * 插件启用方法
     * @return bool
     */
    public function enable()
    {
        // \think\Hook::add('sms_send','addons\\alidayu\\Alidayu');
        // \think\Hook::add('sms_check','addons\\alidayu\\Alidayu');
        return true;
    }

    /**
     * 插件禁用方法
     * @return bool
     */
    public function disable()
    {
        
        return true;
    }

    //发送验证码
	//@sms  验证码发送记录数数据库实例
	//$sms->mobile 手机号码
	//['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => $time]
    public function smsSend($sms)
    {	
    	return $this->sendSms($sms->mobile,$sms->code);
    }

    public function smsCheck($sms){
        return true;
    }
 
    private function  sendSms($phone,$code){
        $conf = get_addon_config('alidayu');
        $params = array ();
        //阿里云的AccessKey
        $accessKeyId = $conf['accesskey'];
 
        //阿里云的Access Key Secret
        $accessKeySecret = $conf['accesskeysecret'];
 
        //要发送的手机号
        $params["PhoneNumbers"] = $phone;
 
        //签名，第三步申请得到
        $params["SignName"] = $conf['signname'];
 
        //模板code，第三步申请得到
        $params["TemplateCode"] = $conf['templatecode'];
 
        if(empty($conf['accesskey']) || empty($conf['accesskeysecret']) || empty($conf['signname']) || empty($conf['templatecode'])){
            return false;
        }

        //模板的参数，注意code这个键需要和模板的占位符一致
        $params['TemplateParam'] = Array (
            "code" => $code
        );
 
        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }
 
        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        $helper = new SignatureHelper();
        try{
            // 此处可能会抛出异常，注意catch
            $content = $helper->request(
                $accessKeyId,
                $accessKeySecret,
                "dysmsapi.aliyuncs.com",
                array_merge($params, array(
                    "RegionId" => "cn-hangzhou",
                    "Action" => "SendSms",
                    "Version" => "2017-05-25",
                ))
            // fixme 选填: 启用https
            // ,true
            );
            $res=array('errCode'=>0,'msg'=>'ok');
            if($content->Message!='OK'){
                $res['errCode']=1;
                $res['msg']=$content->Message;
            }
            return json_encode($res);
        }catch(\Exception $e){
            return false;
        }
 
    }

}
